package com.zxy.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.zxy.pojo.Permission;
import com.zxy.pojo.Role;
import com.zxy.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
    UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 1.查询用户信息，一级用户对应角色，以及角色对应权限
        com.zxy.pojo.User user = userService.findUserByUsername(username);

        if (user == null){//不存在这个用户
            return null; // 返回null给框架，框架会抛异常，进行异常处理，跳转到登录页面
        }
        // 2.构建全限集合
        HashSet<GrantedAuthority> authorities = new HashSet<>();

        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                authorities.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }

        org.springframework.security.core.userdetails.User securityUser = new User(user.getUsername(),user.getPassword(),authorities);
        return securityUser;
    }
}
